package com.itheima;

import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SpringSecurityService implements UserDetailsService {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    //模拟数据库中的用户数据
    public Map<String, User> map = new HashMap<>();

    public void initData(){
        com.itheima.pojo.User user1 = new com.itheima.pojo.User();
        user1.setUsername("admin");
        user1.setPassword(bCryptPasswordEncoder.encode("admin"));

        com.itheima.pojo.User user2 = new com.itheima.pojo.User();
        user2.setUsername("xiaoming");
        user2.setPassword(bCryptPasswordEncoder.encode("1234"));

        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);
    }

    //根据用户名加载用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //初始化数据
        initData();
        //模拟从数据库中查询数据
        User user = map.get(username);
        if (user == null){
            //没有查询到用户
            return null;
        }else {

            //模拟获取数据库中的密码
            String password = user.getPassword();

            //权限和角色集合 泛型GrantedAuthority
            List<GrantedAuthority> list = new ArrayList<>();
            //后期需要查询数据库获取权限和角色
            list.add(new SimpleGrantedAuthority("add"));//授权
            list.add(new SimpleGrantedAuthority("delete"));

            if(username.equals("admin")){
                list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));//授予角色
                list.add(new SimpleGrantedAuthority("add"));//授权add
            }

            /*
              使用框架中封装的User对象
              参数： username
                    数据库中查询到的password
                    list 用户所拥有的权限和角色集合
             */
            org.springframework.security.core.userdetails.User user1 = new org.springframework.security.core.userdetails.User(username,password,list);
            return user1;
        }

    }
}
